import 'package:demo/constants/event_bus_key.dart';
import 'package:demo/constants/route_location.dart';
import 'package:demo/core/router/app_router_delegate.dart';
import 'package:demo/core/router/app_router_information_parser.dart';
import 'package:demo/model/bean/event/page_destroy_bean.dart';
import 'package:demo/utils/connectivity.dart';
import 'package:demo/utils/crash_analysis.dart';
import 'package:demo/utils/event_bus.dart';
import 'package:demo/widget/pull_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/physics.dart';

/// 项目启动根实例
class App extends StatefulWidget {
  final AppRouterDelegate _routerDelegate = AppRouterDelegate();
  final AppRouterInformationParser _informationParser = AppRouterInformationParser();
  final PlatformRouteInformationProvider _platformRouteInformationProvider = PlatformRouteInformationProvider(
    initialRouteInformation: const RouteInformation(location: GUIDE_LOCATION),
  );

  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> with WidgetsBindingObserver {
  @override
  initState() {
    super.initState();
    WidgetsBinding.instance!.addObserver(this);
    initDependencies();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void deactivate() {
    super.deactivate();
  }

  @override
  void dispose() {
    WidgetsBinding.instance!.removeObserver(this);
    relieveDependencies();
    super.dispose();
  }

  /// 这个只做全局的逻辑，不做单独某个页面的业务逻辑，需要在某个页面实现业务
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {

      /// 从后台恢复到前台，或则是用户在别处操作回到本app会触发
      case AppLifecycleState.resumed:
        break;

      /// 页面不可响应的状态，如用户缩放app到后台的过程
      case AppLifecycleState.inactive:
        break;

      /// 进入后台
      case AppLifecycleState.paused:
        break;

      /// 被flutter引擎托管的状态，引擎虽然在运行，但是没有画面出现,可能是第一次初始化，或则是销毁了root视图
      case AppLifecycleState.detached:
        break;
    }
  }

  @override
  void didHaveMemoryPressure() {
    PaintingBinding.instance!.imageCache!.clear();
  }

  /// 注入依赖,如插件
  void initDependencies() async {
    /// 注册全局eventBus事件
    final EventBus eventBusInstance = EventBus.instance;
    eventBusInstance.monitoring<PageDestroyBean>(EVENT_BUS_PAGE_DESTROY_KEY);
  }

  /// 解除依赖
  void relieveDependencies() {
    /// 清除全局的event_bus
    EventBus.instance.destroy();

    /// 清除监听的网络变化
    ConnectivityUtils.instance.destroy();

    /// 清楚bugly监听更新
    CrashAnalysisUtils.instance.destroy();
  }

  /// 配置所有的下来刷新都使用统一的配置,如果有需要在单独配置一份配置进行替换
  RefreshConfiguration _setAllPullFreshConfiguration(Widget child) {
    return RefreshConfiguration(
      headerBuilder: () => ClassicHeader(
        releaseText: "释放手势刷新",
        idleText: "下拉刷新",
        refreshingText: "刷新中…",
        completeText: "刷新成功",
        failedText: "刷新失败",
      ),
      // 配置默认的标题指示器。如果每个页面都有相同的header指示器，则需要设置这个
      footerBuilder: () => ClassicFooter(
        idleText: "上拉加载",
        loadingText: "加载中...",
        noDataText: "暂无更多数据",
        failedText: "加载失败",
        canLoadingText: "释放手势加载",
      ),
      // 配置默认底部指示器
      headerTriggerDistance: 80.0,
      // header 触发刷新触发距离
      springDescription: SpringDescription(stiffness: 170, damping: 16, mass: 1.9),
      // 自定义弹回动画，props 含义见flutter api
      maxOverScrollExtent: 100,
      // 头部最大拖动范围。如果出现冲出视图区域，则设置此属性
      maxUnderScrollExtent: 0,
      // 底部最大拖动范围
      enableScrollWhenRefreshCompleted: true,
      //此属性与 PageView 和 TabBarView 不兼容。如果需要TabBarView左右滑动，需要设置为true。
      enableLoadingWhenFailed: true,
      // 在加载失败的情况下，用户仍然可以通过手势上拉触发更多加载。
      hideFooterWhenNotFull: false,
      // 当视口小于一屏时禁用上拉加载
      enableBallisticLoad: true,
      child: child,
    );
  }

  @override
  Widget build(BuildContext context) {
    return _setAllPullFreshConfiguration(
      MaterialApp.router(
        title: 'Flutter工程基础框架',
        routerDelegate: widget._routerDelegate,
        routeInformationParser: widget._informationParser,
        routeInformationProvider: widget._platformRouteInformationProvider,
      ),
    );
  }
}
